import tkinter as tk
from tkinter import ttk, messagebox
import json
import os
from ..config import Config
import logging
from PIL import Image, ImageTk

logger = logging.getLogger(__name__)

class AccountDialog:
    def __init__(self, parent=None, callback=None):
        self.config = Config()
        self.window = tk.Tk() if parent is None else tk.Toplevel(parent)
        self.callback = callback  # 保存回调函数
        self.window.title("账户设置")
        self.window.geometry("300x200")
        self.window.resizable(False, False)
        
        # 设置窗口图标
        if os.path.exists(self.config.TRAY_ICON_PATH):
            try:
                # 使用 PIL 加载图标
                icon_image = Image.open(self.config.TRAY_ICON_PATH)
                if icon_image.mode != 'RGBA':
                    icon_image = icon_image.convert('RGBA')
                # 转换为 PhotoImage
                icon_photo = ImageTk.PhotoImage(icon_image)
                self.window.iconphoto(True, icon_photo)
                # 保持引用以防止垃圾回收
                self._icon_photo = icon_photo
            except Exception as e:
                logger.error(f"Failed to load window icon: {e}")
        
        self.create_widgets()
        self.load_settings()
        
        # 窗口居中
        self.window.update_idletasks()
        width = self.window.winfo_width()
        height = self.window.winfo_height()
        x = (self.window.winfo_screenwidth() // 2) - (width // 2)
        y = (self.window.winfo_screenheight() // 2) - (height // 2)
        self.window.geometry(f'{width}x{height}+{x}+{y}')

    def create_widgets(self):
        # 创建主框架
        main_frame = ttk.Frame(self.window, padding="20")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))

        # 账户输入
        ttk.Label(main_frame, text="Token:").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.token_var = tk.StringVar()
        self.token_entry = tk.Text(main_frame, height=5, width=30)
        self.token_entry.grid(row=0, column=1, sticky=tk.W, pady=5)

        # 按钮框架
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=2, column=0, columnspan=2, pady=20)

        # 保存按钮
        save_btn = ttk.Button(button_frame, text="保存", command=self.save_settings)
        save_btn.pack(side=tk.LEFT, padx=10)

        # 取消按钮
        cancel_btn = ttk.Button(button_frame, text="取消", command=self.window.destroy)
        cancel_btn.pack(side=tk.LEFT, padx=10)

    def load_settings(self):
        """加载已保存的设置"""
        try:
            if os.path.exists(self.config.ACCOUNT_PATH):
                with open(self.config.ACCOUNT_PATH, 'r', encoding='utf-8') as f:
                    settings = json.load(f)
                    self.token_entry.insert('1.0', settings.get('token', ''))
        except Exception as e:
            logger.error(f"Error loading settings: {e}")

    def save_settings(self):
        """保存设置"""
        try:
            token = self.token_entry.get('1.0', 'end-1c').strip()
            if not token:
                messagebox.showwarning("警告", "Token 不能为空！")
                return

            settings = {
                'token': token
            }
            
            os.makedirs(os.path.dirname(self.config.ACCOUNT_PATH), exist_ok=True)
            with open(self.config.ACCOUNT_PATH, 'w', encoding='utf-8') as f:
                json.dump(settings, f, indent=4)
            
            # 调用保存成功的回调
            if self.callback:
                self.window.after(0, self.callback)
            
            self.window.destroy()
        except Exception as e:
            logger.error(f"Error saving settings: {e}")
            messagebox.showerror("错误", f"保存设置失败: {e}")

    def show(self):
        """显示对话框"""
        self.window.deiconify()
        self.window.focus_force()
        self.window.grab_set()
        self.window.mainloop() 